/**
 * @author Michael
 * @version 1.0
 * @Date 2023/8/23 10:14
 * @Description
 */
import {AITask} from "./AITask/AITask";
import {AIPanel} from "./AIPanel";
import {AITaskGenSkyImg} from "./AITask/AITaskGenSkyImg";
import {AICore} from "./AICore";
import {AIUtils, trimJavascript} from "./AIUtils";
import { LayaAPICode, LayaAPIStatus } from "./AIConfig";
import { LayaAPI } from "./LayaAPI";

type ActionMap = {
    [key: string]: Function
}

export class AIAction {
    private _actionMap: ActionMap = {};
    private _aiCore: AICore;

    constructor() {
        this._aiCore = AICore.inst;
    }

    /**
     * 初始化行为注册
     */
    init() {
        this.add("移动", this.move);
        this.add("创建Sprite3D", ()=>{this.createSprite3D();});
        this.add("创建Sprite", ()=>{this.createSprite();});
        this.add("设置可见",()=>{this.setVisible(true);});
        this.add("设置不可见",()=>{this.setVisible(false);});
        this.add("设置为穿透",()=>{this.setMouseThrough(true);});
        this.add("设置为不穿透",()=>{this.setMouseThrough(false);});

        // this.add("生成图片", ()=>{ return this.createTask('生成图片');});
        // this.add("生成音乐", ()=>{ return this.createTask('生成音乐');});
        // this.add("设置贴图", ()=>{ return this.createTask('设置图片');});

        this.add("创建盒子", async (msg:string)=>{
            let ai = this._aiCore;
            let prompt = `
你是一个js专家,你会把用户输入的指令翻译成js脚本
需求如下：
1. 直接输出js程序,不要任何解释说明，代码也不要注释.
2. 仅仅允许使用下面定义的接口,不允许使用其他接口，不要自创接口.
3. 输出是直接执行的脚本，不要封装成函数.

\`\`\`javascript
interface node{
    setPosition(x:number,y:number,z:number);
    getPosition():{x:number,y:number,z:number};
}
interface Cube extends node{
}
var context:{
    createBox(长度=1,宽度=1,高度=1):Promise<Cube>;
}
\`\`\`

用户指令是:${msg}
你的输出是`;
            ai.startWaitMsg('分析指令中');
            let res: any = await LayaAPI.create().laya_ernie_bot(prompt);
            ai.endWaitMsg();
            if (!res || res.code !== LayaAPICode.CodeSuccess || res.data.status !== LayaAPIStatus.TaskStatusDone) {
                return;
            }
    
            let str = res.data.content as string;
            str = trimJavascript(str);
            if(str && str.length>10){
            }
            debugger
        });
        this.add("创建面片", ()=>{this.createNode("Plane");});
        this.add("创建球",   ()=>{this.createNode("Sphere");});

        this.add("生成天空盒",   ()=>new AITaskGenSkyImg());
        //this.add("设置天空盒",   ()=>new AITaskSetSkyBox());
        this.add("打招呼",   ()=>{AIPanel.ins.addMsg('你好！很高兴和你交流，请问有什么我可以帮助你的吗？',-2);});
        this.add("生成模型", ()=>{AIPanel.ins.addMsg('你好，暂时不支持生成模型.',-2);});
        this.add("生成视频", ()=>{AIPanel.ins.addMsg('你好，暂时不支持生成视频.',-2);});
        this.add("称赞",     ()=>{AIPanel.ins.addMsg('谢谢您的认可！如果您在使用过程中有任何问题或建议，都可以随时告诉我。我会尽快进行优化和改进。',-2);});
        this.add("打开镜头眩光", (msg:string)=>{
            if(msg.includes('镜头炫光') || msg.includes('镜头眩光')){
                AIPanel.ins.addMsg('因为要下载资源，暂时没有。但很快就要实现了.',-2);
            }
            else{
                AIPanel.ins.addMsg('你是要打开镜头眩光么，因为要下载资源，暂时没有。但很快就要实现了.',-2);
            }
        });
        this.add("关闭镜头眩光", ()=>{AIPanel.ins.addMsg('因为要下载资源，暂时没有。但很快就要实现了.',-2);});
        this.add("怎么把摄像机对齐到编辑摄像机", ()=>{AIPanel.ins.addMsg('ctrl+shift+F',-1);});
        this.add("怎么添加后处理", ()=>{AIPanel.ins.addMsg('你要添加后处理?',-1);});

        //this.add("createtree",()=>{return new AITaskTree();});

        this.add("开始试玩",()=>{(Editor as any).hotkeyManager.emit("play");});
        this.add("打开图集打包工具窗口",()=>{(Editor as any).hotkeyManager.emit("TexturePacker");});
        this.add("打开按钮皮肤工具窗口",()=>{(Editor as any).hotkeyManager.emit("MakeButtonSkin");});
        this.add("打开动画烘焙工具窗口",()=>{(Editor as any).hotkeyManager.emit("BakeAnimation");});
        this.add("打开骨骼转换工具窗口",()=>{(Editor as any).hotkeyManager.emit("SkeletonConverter");});
        this.add("save",               ()=>{(Editor as any).hotkeyManager.emit("save")});

        this.add("打开项目设置",()=>{Editor.panelManager.showPanel('ProjectSettingsPanel');});
        this.add("打开发布面板",()=>{Editor.panelManager.showPanel('BuildSettingsPanel');});
        this.add("打开动画面板",()=>{Editor.panelManager.showPanel('TimelinePanel');});
        this.add("打开小部件面板",()=>{Editor.panelManager.showPanel('WidgetsPanel');});
        this.add("切换到层级面板",()=>{Editor.panelManager.showPanel('HierarchyPanel');});
        this.add("切换到控制台面板",()=>{Editor.panelManager.showPanel('ConsolePanel');});
        this.add("切换到属性设置面板",()=>{Editor.panelManager.showPanel('InspectorPanel');});
        this.add("切换到动画状态机面板",()=>{Editor.panelManager.showPanel('AnimatorControllerPanel');});

        this.add("设置为正交视角",()=>{Editor.scene.runScript('AI_CameraCtrl.cmd', 'orthographic', true).then(ret=>{});});
        this.add("设置为透视模式",()=>{Editor.scene.runScript('AI_CameraCtrl.cmd', 'orthographic', false).then(ret=>{});});

        this.add("打开显示设置面板",()=>{Editor.panelManager.postMessage("ScenePanel", "showSceneViewSettingsDialog", "canvas");});
        this.add("烘焙IBL",()=>{Editor.panelManager.postMessage("ScenePanel", "startBake", false);});
        this.add("清空控制台",()=>{Editor.panelManager.postMessage("ConsolePanel", "clear");});
        this.add("模型位移模式",()=>{Editor.panelManager.postMessage("ScenePanel", "changeToolType", "obj_move");});
        this.add("模型旋转模式",()=>{Editor.panelManager.postMessage("ScenePanel", "changeToolType", "obj_rotate");});
        this.add("模型缩放模式",()=>{Editor.panelManager.postMessage("ScenePanel", "changeToolType", "obj_scale");});
        this.add("模型混合编辑模式",()=>{Editor.panelManager.postMessage("ScenePanel", "changeToolType", "obj_transform");});
        this.add("位置归零",()=>{
            AIUtils.forEachSelect((data: any)=>{
                if(data.is3d){
                    let pos = data.props.transform.localPosition;
                    pos.x=0;pos.y=0;pos.z=0;
                }else{
                    data.props.x = data.props.y = 0;
                }
            });
        });
        this.add("旋转归零",()=>{
            AIUtils.forEachSelect((data: any)=>{
                if(data.is3d){
                    let rot = data.props.transform.localRotationEuler;
                    rot.x=0;rot.y=0;rot.z=0;
                }else{
                    data.props.rotation = 0;
                }
            });
        });
        this.add("缩放归一",()=>{
            AIUtils.forEachSelect((data: any)=>{
                if(data.is3d){
                    let s = data.props.transform.localScale;
                    s.x=1;s.y=1;s.z=1;
                }else{
                    data.props.scaleX = data.props.scaleY = 1;
                }
            });
        });
        this.add("添加一个角色",()=>{});

        this.add("打开雾",()=>{
            if(Editor.scene.rootNode.children[0].name == "Scene3D"){
                Editor.scene.rootNode.children[0].props.enableFog = true;
            }
        });

        this.add("关闭雾",()=>{
            if(Editor.scene.rootNode.children[0].name == "Scene3D"){
                Editor.scene.rootNode.children[0].props.enableFog = false;
            }
        });

        this.add("确认",()=>{
        });

        this.add("否认",()=>{
        });

        this.add("取消",()=>{
        });

        this.add("聚焦对象",()=>{
            let sel: ReadonlyArray<any> = Editor.scene.getSelection()
            if(sel && sel[0]){
                Editor.scene.runScript('AI_CameraCtrl.cmd', 'focus', ''+sel[0].id).then(ret=>{});
            }
        });


    }

    /**
     * 设置鼠标是否穿透
     * @param value
     */
    setMouseThrough(value: boolean){
        AIUtils.forEachSelect((data: any)=>{
            if(!data.is3d){
                data.props.mouseThrough = value;
            }
        });
    }
    createSprite3D(){
        let root: any = Editor.scene.rootNode.children[0];
        Editor.scene.createNode("Sprite3D", {name: "Sprite3D"}, root).then((newNode)=>{
            if (newNode) {
                Editor.scene.addNode(root, newNode, -1).then(()=>{
                    Editor.scene.setSelection(newNode);
                });
            }
        });
    }

    createSprite(){
        let root: any = Editor.scene.rootNode.children[1];
        Editor.scene.createNode("Sprite", {name: "Sprite"}, root).then((newNode)=>{
            if (newNode) {
                Editor.scene.addNode(root, newNode, -1).then(()=>{
                    Editor.scene.setSelection(newNode);
                });
            }
        });
    }

    private setVisible(value: boolean){
        AIUtils.forEachSelect((data: any)=>{
            if(data.is3d){
                data.props.active = value;
            }else{
                data.props.visible = value;
            }
        });
    }
    private async createNode(type: string) {
        const scene = Editor.scene;
        let newNode = await scene.createNode(type, {name: type})
        if (newNode) {
            scene.addNode(null, newNode);
            scene.setSelection(newNode);
        }
        return newNode;
    }

    private move(msg: string, parsed: any){
        let dist:number = parsed.params.number?.[0]*1;
        if(isNaN(dist))dist=null;

        let cmd = msg;
        let isRot=false;
        if(cmd.indexOf('转')>=0 || cmd.indexOf('zhuan')>=0){
            isRot=true;
        }
        if(cmd.indexOf('前')>=0){
            Editor.scene.runScript('AI_CameraCtrl.cmd', 'foward', dist).then(ret=>{});
        }else if(cmd.indexOf('后')>=0){
            Editor.scene.runScript('AI_CameraCtrl.cmd', 'backward', dist).then(ret=>{});
        }else if(cmd.indexOf('左')>=0){
            (isRot?Editor.scene.runScript('AI_CameraCtrl.cmd', 'rotateleft', dist):Editor.scene.runScript('AI_CameraCtrl.cmd', 'left', dist)).then(ret=>{});
        }else if(cmd.indexOf('右')>=0){
            (isRot?Editor.scene.runScript('AI_CameraCtrl.cmd', 'rotateright', dist):Editor.scene.runScript('AI_CameraCtrl.cmd', 'right', dist)).then(ret=>{});
        }else if(cmd.indexOf('上')>=0){
            (isRot?Editor.scene.runScript('AI_CameraCtrl.cmd', 'rotateup', dist):Editor.scene.runScript('AI_CameraCtrl.cmd', 'up', dist)).then(ret=>{});
        }else if(cmd.indexOf('下')>=0){
            (isRot?Editor.scene.runScript('AI_CameraCtrl.cmd', 'rotatedown', dist):Editor.scene.runScript('AI_CameraCtrl.cmd', 'down', dist)).then(ret=>{});
        }
    }


    /**
     * 添加一个行为
     * @param name
     * @param func
     */
    add(name: string, func: Function) {
        this._actionMap[name] = func
    }

    /**
     * 获取定义的行为数组
     */
    getActionsDefine(): string[] {
        return Object.keys(this._actionMap);
    }

    /**
     * 是否包含指令
     * @param label
     */
    contain(label: string):boolean{
        return !!this._actionMap[label];
    }
    /**
     * 执行一个行为
     * @param name
     * @param msg
     * @param parsed
     */
    run(name: string, msg: {msg:string,handled:boolean}, parsed: any) {
        if (this._actionMap[name]) {
            msg.handled = true;
            return this._actionMap[name](msg.msg, parsed);
        }
        return null;
    }
}
